package com.jlhlyby.concurrence;

public class ProductCustomer {
    ///常量 可为库存
    private static int MAX_VALUE = 10;
    private int size = 0;
    final Object object = new Object();


    /**
     * 生产者方法
     */
    public  void  product() throws InterruptedException {
        synchronized (object){
            while (MAX_VALUE == size){
                System.out.println("仓库已满，【生产者】： 暂时不能执行生产任务!");
                object.wait();
            }
            size++;
            System.out.println("生产者：生产力一个产品 现在仓库存量有："+size);
            object.notifyAll();
        }
    }

    /**
     * 消费者方法
     */
    public void customer() throws InterruptedException {
        synchronized (object){
            while (size == 0){
                System.out.println("仓库无货，消费者：暂时不能执行消费任务");
                object.wait();
            }
            size--;
            System.out.println("【消费者】：消费了一个产品【现仓储量为】:" + size);
            object.notifyAll();
        }
    }

    public static void main(String[] args) {
        ProductCustomer con = new ProductCustomer();

        //生产
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
//                    for (int i = 0; i < 100; i++) {
                    while (true) {
                        con.product();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

        //消费
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(10);
//                    for (int i = 0; i < 100; i++) {
                    while (true) {
                        con.customer();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
}
